package org.oims.simpleserver.listener;

import org.apache.commons.lang3.StringUtils;
import org.oims.simpleserver.entities.db.User;
import org.oims.simpleserver.services.UserService;
import org.oims.simpleserver.session.HttpSessionHub;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.*;

@WebListener
@Controller
public class HttpSessionCDListener implements HttpSessionListener, HttpSessionAttributeListener {
    private HttpSessionHub sessionHub;
    private UserService userService;

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        se.getSession().setMaxInactiveInterval(1200);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        HttpSession session = se.getSession();
        User user = (User) session.getAttribute("user");
        if(user != null){
            String MpNo = user.getMpNo();
            sessionHub.remove(MpNo);
            userService.removeTokenByMpNo(MpNo);
        }
    }

    @Override
    public void attributeAdded(HttpSessionBindingEvent se) {
        String attrName = se.getName();
        if(StringUtils.equals(attrName, "user")){
            User user = (User) se.getValue();
            sessionHub.put(user.getMpNo(), se.getSession());
            userService.removeTokenByMpNo(user.getMpNo());
        }
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent se) {

    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent se) {

    }

    @Autowired
    public void setSessionHub(HttpSessionHub sessionHub) {
        this.sessionHub = sessionHub;
    }

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }
}
